package de.sendorian.util.io;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.apache.log4j.Logger;

import de.sendorian.util.matcher.FileTypeMatchers;

public class FileWriter {

	private static Logger logger = Logger.getLogger(FileWriter.class.getName());

	public boolean deleteFile(String path, String fileName) {
		File file = new File(path, fileName);
		if (!file.exists()) {
			return false;
		}
		file.delete();
		return true;
	}


	public boolean write(byte[] data, String path, String fileName) throws IOException {
		long start = System.currentTimeMillis();
		File dir = createDir(path);

		OutputStream out = null;
		try {
			File file = new File(dir, fileName);
			if (file.exists()) {
				logger.info("The file \"" + path + java.io.File.separator + fileName
				    + "\" already exists. Skipping.");
				return false;
			}

			file.createNewFile();
			out = new BufferedOutputStream(new FileOutputStream(file));
			out.write(data);
			out.flush();
			logger.debug("   Time for Saving file: " + (System.currentTimeMillis() - start)
			    + " [ms]");
			return true;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
				}
			}
		}
	}


	public File createDir(String path) {
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}


	public List<String> deflateArchiveFlat(String path, String fileName) throws ZipException,
	    IOException {
		ZipFile zipFile = new ZipFile(new File(path, fileName));

		FileReader fileReader = new FileReader();
		Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
		List<String> fileNames = new ArrayList<String>();
		while (zipEntries.hasMoreElements()) {
			ZipEntry zipEntry = zipEntries.nextElement();
			String zipEntryName = zipEntry.getName();

			// do not create subdirectories, only use the file name
			if (zipEntryName.contains(File.separator)) {
				zipEntryName = zipEntryName.substring(zipEntryName.indexOf(File.separatorChar));
			}

			if (!zipEntry.isDirectory() && !FileTypeMatchers.ignoredFiles().matches(zipEntryName)) {
				byte[] data = fileReader.getFile(zipFile.getInputStream(zipEntry));
				fileNames.add(zipEntryName);
				write(data, path, zipEntryName);
			}
		}
		return fileNames;
	}
}
